package cn.xuyun.cc.tcp.util;

import java.io.File;
import java.io.FileOutputStream;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AES {

	public final static String keys[][] = { 
		{ "tr8v7vghw7v278vn2v8239vh29vud08u", "qq1eezgxijvlm2op" },

	};

	// 加密
	public static byte[] Encrypt(byte[] sSrc, int keysIndex) throws Exception {
		String sKey = keys[keysIndex][0];
		String ivstr = keys[keysIndex][1];
		SecretKeySpec key=new SecretKeySpec(sKey.getBytes(), "AES");
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// "算法/模式/补码方式"
		IvParameterSpec iv = new IvParameterSpec(ivstr.getBytes());// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
		cipher.init(Cipher.ENCRYPT_MODE,key, iv);
		byte[] encrypted = cipher.doFinal(sSrc);

		return encrypted; 
	}

	// 解密
	public static byte[] Decrypt(byte[] sSrc, int keysIndex) throws Exception {
		try {
			String sKey = keys[keysIndex][0];
			String ivstr = keys[keysIndex][1];
			SecretKeySpec key=new SecretKeySpec(sKey.getBytes(), "AES");
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			IvParameterSpec iv = new IvParameterSpec(ivstr.getBytes());
			cipher.init(Cipher.DECRYPT_MODE, key, iv);
			byte[] encrypted1 =sSrc;
			try {
				byte[] original = cipher.doFinal(encrypted1);
				return original;
			} catch (Exception e) {
				System.out.println(e.toString());
				return null;
			}
		} catch (Exception ex) {
			System.out.println(ex.toString());
			return null;
		}
	}
	
	
	public static String hexDump(byte[] input)
	{
		StringBuffer sb=new StringBuffer();
		for(int i=0;i<input.length;i++)
		{
			sb.append(Integer.toHexString(input[i]&0xff));
		}
		return sb.toString();
	}

	public static void main(String[] args) throws Exception {
		byte[] sSrc="hello world".getBytes();
		System.out.println("加密前的字节串是："+hexDump(sSrc));
		
		
		// 加密
		long lStart = System.currentTimeMillis();
		byte[] enString = AES.Encrypt(sSrc, 0);
		System.out.println("加密后的字节串是："+hexDump(enString));

		
		FileOutputStream fos=new FileOutputStream(new File("decode"));
		
		fos.write(enString);
		
		fos.flush();
		
		fos.close();
		
		
		long lUseTime = System.currentTimeMillis() - lStart;
		System.out.println("加密耗时：" + lUseTime + "毫秒");
		// 解密
		lStart = System.currentTimeMillis();
		byte[] DeString = AES.Decrypt(enString, 0);
		System.out.println("解密后的字节串是：" + hexDump(DeString));
		System.out.println("解密后的字符串是：" + new String(DeString));
		lUseTime = System.currentTimeMillis() - lStart;
		System.out.println("解密耗时：" + lUseTime + "毫秒");
		
		
	}
}